//
//  BaseChartView.m
//  ChartRefactor
//
//  Created by CaoJun on 15/3/13.
//  Copyright (c) 2015年 CaoJun. All rights reserved.
//

#import "BaseChartView.h"
#import "ChartCanvas.h"

using namespace ytx;

@interface InjectEntity : NSObject

@property (nonatomic, strong) PainterBase * painter;
@property (nonatomic, strong) PainterView * painterView;

@end

@implementation InjectEntity


@end

@interface BaseChartView() <UIGestureRecognizerDelegate>
@property (nonatomic) UILongPressGestureRecognizer *longPressGestureRecognizer;
@property (nonatomic) UIPinchGestureRecognizer *pinchGestureRecognizer;
@property (nonatomic, strong) NSMutableDictionary *injectMap;
@property (nonatomic, assign) BaseChartPanDirection panDirection;

@end

@implementation BaseChartView

- (PainterView *) rectPainterView{
    if (_rectPainterView == nil) {
        _rectPainterView = [[PainterView alloc] initWithFrame:self.bounds];
        _rectPainterView.translatesAutoresizingMaskIntoConstraints = NO;
        _rectPainterView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _rectPainterView;
}

- (PainterView *) kLinePainterView{
    if (_kLinePainterView == nil) {
        _kLinePainterView = [[PainterView alloc] initWithFrame:self.bounds];
        _kLinePainterView.translatesAutoresizingMaskIntoConstraints = NO;
        _kLinePainterView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _kLinePainterView;
}

- (PainterView *) linePainterView{
    if (_linePainterView == nil) {
        _linePainterView = [[PainterView alloc] initWithFrame:self.bounds];
        _linePainterView.translatesAutoresizingMaskIntoConstraints = NO;
        _linePainterView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _linePainterView;
}

- (PainterView *) indexPainterView{
    if (_indexPainterView == nil) {
        _indexPainterView = [[PainterView alloc] initWithFrame:self.bounds];
        _indexPainterView.translatesAutoresizingMaskIntoConstraints = NO;
        _indexPainterView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _indexPainterView;
}

- (PainterTextView *) textPainterView{
    if (_textPainterView == nil) {
        _textPainterView = [[PainterTextView alloc] initWithFrame:self.bounds];
        _textPainterView.translatesAutoresizingMaskIntoConstraints = NO;
        _textPainterView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _textPainterView;
}

- (PainterCrosshairsView *) crosshairsPainterView{
    if (_crosshairsPainterView == nil) {
        _crosshairsPainterView = [[PainterCrosshairsView alloc] initWithFrame:self.bounds];
        _crosshairsPainterView.translatesAutoresizingMaskIntoConstraints = NO;
        _crosshairsPainterView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _crosshairsPainterView;
}

- (PainterUserAVGView *) userAVGPainterView{
    if (_userAVGPainterView == nil) {
        _userAVGPainterView = [[PainterUserAVGView alloc] initWithFrame:self.bounds];
        _userAVGPainterView.translatesAutoresizingMaskIntoConstraints = NO;
        _userAVGPainterView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _userAVGPainterView;
}

- (PainterUserView *) userPainterView{
    if (_userPainterView == nil) {
        _userPainterView = [[PainterUserView alloc] initWithFrame:self.bounds];
        _userPainterView.translatesAutoresizingMaskIntoConstraints = NO;
        _userPainterView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _userPainterView;
}


- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [self constructor];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        [self constructor];
    }
    return self;
}

-(void)constructor
{
    self.injectMap = [NSMutableDictionary dictionary];
    
//    self.backgroundColor = [UIColor colorWithRed:0.164 green:0.180 blue:0.211 alpha:1];
    
    self.indexPosition = new ViewModelIndexPosition();
    
    CGRect bounds = self.bounds;
    
    RectangleOption option = RectangleOption();
    
    Rectangle rectMain(bounds.size.width, bounds.size.height, option);
    
    self.indexPosition->setRectangle(rectMain);
    
    self.uiPanGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlerPan:)];
    
    [self addGestureRecognizer:self.uiPanGestureRecognizer];
    self.uiPanGestureRecognizer.delegate = self;
    
    self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    self.longPressGestureRecognizer.minimumPressDuration = MinimumPressDuration;
    [self addGestureRecognizer:self.longPressGestureRecognizer];
    
    self.pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
    [self addGestureRecognizer:self.pinchGestureRecognizer];
}

- (void)addPanGesture
{
    [self addGestureRecognizer:self.uiPanGestureRecognizer];
}

- (void)removePanGesture
{
    [self removeGestureRecognizer:self.uiPanGestureRecognizer];
}

-(void)dealloc
{
    if (_indexPosition != NULL){
        delete _indexPosition;
        _indexPosition = NULL;
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self render];
}

- (void) render
{

}

- (void) resize
{
    self.indexPosition->getRectangle().resize(self.bounds.size.width, self.bounds.size.height);
}

- (BOOL) hasData
{
    return false;
}

- (void) drawCrosshairsWithX:(NSNumber *) dx withY:(NSNumber *) dy
{
    if (_crosshairsPainterView != nil) {
        [self.crosshairsPainterView drawCrosshairs:self.indexPosition withPainter: [PainterCrosshairs new] withX:dx withY:dy];
    }
}

- (void) drawCrosshairsWithX:(NSNumber *) dx withY:(NSNumber *) dy isDrawBottomText:(BOOL) isBottomText
{
    if (_crosshairsPainterView != nil) {
        [self.crosshairsPainterView drawCrosshairs:self.indexPosition withPainter: [PainterCrosshairs new] withX:dx withY:dy];
    }
}

- (void) drawCrosshairsWithX:(NSNumber *) dx
{
    if (_crosshairsPainterView != nil) {
        [self.crosshairsPainterView drawCrosshairs:self.indexPosition withPainter: [PainterCrosshairs new] withX:dx];
    }
}

- (void) clearCrosshairs
{
    if (_crosshairsPainterView != nil) {
       [self.crosshairsPainterView clear];
    }
}

- (void) drawTopSideTextWithX:(CGFloat) dx
{
    if (_textPainterView != nil){
        [self.textPainterView drawTopSideTextWithX:dx];
    }
}

- (void) resetTopSideText
{
    if (_textPainterView != nil){
        [self.textPainterView resetTopSideText];
    }
}

-(void)paint
{
    for (NSString * key in self.injectMap) {
        InjectEntity * entity = self.injectMap[key];
        [entity.painterView paint: self.indexPosition withPainter: entity.painter ];
    }
}

- (void) clear
{
    for (NSString * key in self.injectMap) {
        InjectEntity * entity = self.injectMap[key];
        [entity.painterView clear];
    }
}

#pragma mark - inject
- (BOOL) injectWithKey:(NSString *)key painterBaseView:(PainterView *) painterView painterBase:(PainterBase *) painterBase
{
    return [self injectWithKey:key painterBaseView:painterView painterBase:painterBase atIndex:self.subviews.count];
}
- (BOOL) injectWithKey:(NSString *)key painterBaseView:(PainterView *) painterView painterBase:(PainterBase *) painterBase atIndex:(NSUInteger) index
{
    if (self.injectMap[key]) {
        return NO;
    }
    
    InjectEntity * entity = [InjectEntity new];
    
    painterView.indexPosition = self.indexPosition;
    
    entity.painterView = painterView;
    entity.painter = painterBase;
    
    [self.injectMap setObject:entity forKey:key];
    
    [self insertSubview:painterView atIndex:index];
    
    return YES;
}
- (BOOL) disinjectWithKey:(NSString *)key
{
    if (!self.injectMap[key]) {
        return NO;
    }
    [self.injectMap removeObjectForKey:key];
    return YES;
}


#pragma mark - gesture
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    UIView *otherRecognizerView = otherGestureRecognizer.view;
    if ([otherRecognizerView isKindOfClass:NSClassFromString(@"MainChartKLineView")] || [otherRecognizerView isKindOfClass:NSClassFromString(@"MinorChartKLineView")]) {
        return NO;
    }
    return YES;
}

- (void) handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
        {
            CGPoint p = [gestureRecognizer locationInView:self];

            [self longPressBegin:@(p.x)];
            if ([self.delegate respondsToSelector:@selector(longPressBegin: withX: withY:)]) {
                //TODO("现在Y坐标取得是手势位置的y坐标，需改为高低处坐标");
                [self.delegate longPressBegin:self withX:@(p.x) withY:@(p.y)];
            }
            break;
        }
        case UIGestureRecognizerStateChanged:
        {
            CGPoint p = [gestureRecognizer locationInView:self];
            [self longPressChanged:@(p.x)];
            if ([self.delegate respondsToSelector:@selector(longPressChanged: withX: withY:)]) {
                [self.delegate longPressChanged:self withX:@(p.x) withY:@(p.y)];
            }
            break;
        }
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:
        {
            // 十字光标长按后不消失
//            [self longPressCancelledOrEnded];
//            if ([self.delegate respondsToSelector:@selector(longPressCancelledOrEnded:)]) {
//                [self.delegate longPressCancelledOrEnded:self];
//            }
            break;
        }
        default:
            break;
    }
}

- (void) longPressBegin:(NSNumber *) dx
{

}
- (void) longPressChanged:(NSNumber *) dx
{

}
- (void) longPressCancelledOrEnded
{

}


- (void)handlerPan:(UIPanGestureRecognizer *)gesture
{
    CGPoint point = [gesture translationInView:self];
    NSLog(@"--%@",NSStringFromCGPoint(point));
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            if ([self.delegate respondsToSelector:@selector(longPressCancelledOrEnded:)]) {
                [self.delegate longPressCancelledOrEnded:self];
            }
            
            if (fabs(point.y) > fabs(point.x)) {
                if (point.y < 0) {
                    self.panDirection = BaseChartPanDirectionUp;
                } else if (point.y > 0){
                    self.panDirection = BaseChartPanDirectionDown;
                }
                
            } else {
                if (point.x < 0) {
                    self.panDirection = BaseChartPanDirectionLeft;
                } else if (point.x > 0){
                    self.panDirection = BaseChartPanDirectionRight;
                }
            }
            if (self.panDirection == BaseChartPanDirectionLeft || self.panDirection == BaseChartPanDirectionRight) {
                [self panBegin:gesture];
            }
            break;
        case UIGestureRecognizerStateChanged:
        {
            if (self.panDirection == BaseChartPanDirectionLeft || self.panDirection == BaseChartPanDirectionRight) {
                [self panChanged:gesture];
            }
            break;
        }
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:
        {
            self.panDirection = BaseChartPanDirectionNone;
            if (self.panDirection == BaseChartPanDirectionLeft || self.panDirection == BaseChartPanDirectionRight) {
                [self panCancelledOrEnded:gesture];
            }
            break;
        }
        default:
            break;
    }
}

- (void) panBegin:(UIPanGestureRecognizer *)gesture
{
    if ([self.delegate respondsToSelector:@selector(panBegin: withGesture:)]) {
        [self.delegate panBegin:self withGesture:gesture];
    }
}
- (void) panChanged:(UIPanGestureRecognizer *)gesture
{
    if ([self.delegate respondsToSelector:@selector(panChanged: withGesture:)]) {
        [self.delegate panChanged:self withGesture:gesture];
    }
}
- (void) panCancelledOrEnded:(UIPanGestureRecognizer *)gesture
{    
    if ([self.delegate respondsToSelector:@selector(panChanged: withGesture:)]) {
        [self.delegate panCancelledOrEnded:self withGesture:gesture];
    }
    
}

- (void) handlePinch:(UIPinchGestureRecognizer *)gesture;
{
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            [self pinchBegin:gesture];
            break;
        case UIGestureRecognizerStateChanged:
        {
            [self pinchChanged:gesture];
            break;
        }
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:
        {
            [self pinchCancelledOrEnded:gesture];
            break;
        }
        default:
            break;
    }
}

- (void) pinchBegin:(UIPinchGestureRecognizer *)gesture
{
    CGFloat scale = gesture.scale;

    if ([self.delegate respondsToSelector:@selector(pinchBegin: withScale: withGesture:)]) {
        [self.delegate pinchBegin:self withScale:scale withGesture:gesture];
    }
}
- (void) pinchChanged:(UIPinchGestureRecognizer *)gesture
{
    CGFloat scale = gesture.scale;

    if ([self.delegate respondsToSelector:@selector(pinchBegin: withScale: withGesture:)]) {
        [self.delegate pinchChanged:self withScale:scale withGesture:gesture];
    }
}
- (void) pinchCancelledOrEnded:(UIPinchGestureRecognizer *)gesture
{
    if ([self.delegate respondsToSelector:@selector(pinchCancelledOrEnded: withGesture:)]) {
        [self.delegate pinchCancelledOrEnded:self withGesture:gesture];
    }
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (gestureRecognizer == self.uiPanGestureRecognizer) {
        if ([self.delegate respondsToSelector:@selector(chartView:panGestureRecognizer:shouldReceiveTouch:)]) {
            return [self.delegate chartView:self panGestureRecognizer:self.uiPanGestureRecognizer shouldReceiveTouch:touch];
        }
    } else if (gestureRecognizer == self.longPressGestureRecognizer) {
        if ([self.delegate respondsToSelector:@selector(chartView:longPressGestureRecognizer:shouldReceiveTouch:)]) {
            return [self.delegate chartView:self longPressGestureRecognizer:self.longPressGestureRecognizer shouldReceiveTouch:touch];
        }
    } else if (gestureRecognizer == self.pinchGestureRecognizer) {
        if ([self.delegate respondsToSelector:@selector(chartView:pinchGestureRecognizer:shouldReceiveTouch:)]) {
            return [self.delegate chartView:self pinchGestureRecognizer:self.pinchGestureRecognizer shouldReceiveTouch:touch];
        }
    }

    return YES;
}

- (void)setPanDirection:(BaseChartPanDirection)panDirection
{
    if (_panDirection != panDirection) {
        _panDirection = panDirection;
        if (panDirection != BaseChartPanDirectionNone && [self.delegate respondsToSelector:@selector(panDirection:)]) {
            [self.delegate panDirection:panDirection];
        }
    }
}

@end
